/*
** get_next_line.c for get_next_line in /home/vanet_c//get_next_line
**
** Made by charles-edouard vanet
** Login   <vanet_c@epitech.net>
**
** Started on  Mon Nov 26 13:31:16 2012 charles-edouard vanet
** Last update Fri Dec 14 18:49:53 2012 charles-edouard vanet
*/

#include	<stdlib.h>
#include	<unistd.h>
#include	"my.h"

char		*get_result(char *stock, int nbr_files)
{
  char		*result;
  static int	i = 0;
  int		j;
  static int	file_nb = 0;

  j = 0;
  if (stock[i] == '\0')
    {
      file_nb++;
      if (nbr_files == file_nb)
	free(stock);
      return (NULL);
    }  
  if ((result = malloc(sizeof(char) * GNL_MAX_READ + 1)) == NULL)
    return (NULL);
  while (stock[i] != '\n' && stock[i] != '\0' && j < GNL_MAX_READ)
    result[j++] = stock[i++];
  result[j] = '\0';
  if (stock[i] == '\n')
    i++;
  return (result);
}

char		*get_next_line(const int fd, int nbr_files)
{
  static char	*result = NULL;
  static int	i = 0;
  char		buff[GNL_MAX_READ + 1];
  int		len;
  int		j;

  j = 0;
  if (GNL_MAX_READ <= 0)
    return (NULL);
  if (result == NULL)
    {
      if ((result = malloc(1)) == NULL)
	return (NULL);
      result[0] = '\0';
    }
  if ((len = read(fd, buff, GNL_MAX_READ)) == -1)
    return (NULL);
  buff[len] = 0;
  len = len + i;
  result = my_realloc(result, len);
  while (buff[j])
    result[i++] = buff[j++];
  result[i] = '\0';
  return (get_result(result, nbr_files));
}
